/*
 * Entry point for the simulation.  The program will accept several command
 * line arguments for debugging purposes.  The simulation is started 
 * through the cpu.run operation once the console and printers have been 
 * created.
 * */

package simulation;

import cpu.components.CPU;

public class Main {

	public static CPU cpu;
	
	static final int DEFAULT_SLEEP_INTERVAL = 0;
	
	public static void main( String[] args ) {
		boolean debug = false;
		int sleep_interval = DEFAULT_SLEEP_INTERVAL;
		
		for( int i = 0; i < args.length; i++ ) {
			String arg = args[i];
			
			if( arg.compareTo( "-debug" ) == 0 )
				debug = true;
			else if( arg.contains("=") ) {
				String param = arg.substring( 0, arg.indexOf( "=" ) );
				String value = arg.substring( arg.indexOf( "=" ) + 1 );
				
				if( param.compareTo( "-sleep" ) == 0 ) {
					try {
						sleep_interval = Integer.parseInt( value );
					} catch( Exception ex ) {
						sleep_interval = DEFAULT_SLEEP_INTERVAL;
					}
				}
			}
		}

		int total_cycles = 0;

		// initialization
		ui.Console console = new ui.Console( );
		
		//System.out.println( "Width: " + console.getWidth( ) ); 
		//System.out.println( "Height: " + ( 900 - console.getHeight( ) ) );
		
		ui.Printer printer = new ui.Printer( 0, console.getHeight( ), console.getWidth( ), 900 - console.getHeight( ) );
		
		cpu = new CPU( console, printer );
		console.cpu = cpu;
		
		if( sleep_interval > 500 ) {
			cpu.LATENCY.fromJavaInt( 10 );	// 1000
		} else if( sleep_interval > 200 ) {
			cpu.LATENCY.fromJavaInt( 9 );	// 500
		} else if( sleep_interval > 100 ) {
			cpu.LATENCY.fromJavaInt( 8 );	// 200
		} else if( sleep_interval > 50 ) {
			cpu.LATENCY.fromJavaInt( 7 );	// 100
		} else if( sleep_interval  > 20 ) {
			cpu.LATENCY.fromJavaInt( 6 );	// 50
		} else if( sleep_interval  > 10 ) {
			cpu.LATENCY.fromJavaInt( 5 );	// 20
		} else if( sleep_interval  > 5 ) {
			cpu.LATENCY.fromJavaInt( 4 );	// 10
		} else if( sleep_interval  > 2 ) {
			cpu.LATENCY.fromJavaInt( 3 );	// 5
		} else if( sleep_interval  > 1 ) {
			cpu.LATENCY.fromJavaInt( 2 );	// 2
		} else if( sleep_interval  > 0 ) {
			cpu.LATENCY.fromJavaInt( 1 );	// 1
		} else {
			cpu.LATENCY.fromJavaInt( 0 );	// 0
		}

		//cpu.sleep_interval = sleep_interval;
		
		if( debug )
			cpu.startDebug();
		else
			cpu.stopDebug();
		
		console.sleep_interval = sleep_interval;

		printer.show( );
		console.show( );

		cpu.run( );
		
		// terminating, but code unreachable
		System.exit( 0 );
	}
}
